package  
{
	import flare.basic.*;
	import flare.collisions.*;
	import flare.core.*;
	import flare.system.*;
	import flare.utils.*;
	import flash.display.*;
	import flash.events.*;
	import flash.geom.*;
	
	[SWF(frameRate = 120, backgroundColor = 0x808080, width = 800, height = 600 )]
	
	/**
	 * ...
	 * @author Ariel Nehmad
	 */
	public class Test13_Collisions extends Sprite
	{
		private var scene:Scene3D;
		private var level:Pivot3D;
		private var player:Pivot3D;
		private var collisions:SphereCollision;
		
		public function Test13_Collisions() 
		{
			// creates the scene.
			scene = new Viewer3D( this );
			
			// loads 3d objects.
			level = scene.addChildFromFile( "level.f3d" );
			player = scene.addChildFromFile( "walker.f3d" );
			
			// listen to complete event.
			scene.addEventListener( Scene3D.COMPLETE_EVENT, completeEvent );
			
			// some optional configurations.
			scene.defaultLight.setRotation( 45, -45, 45 );
			scene.antialias = 1;			
		}
		
		private function completeEvent(e:Event):void 
		{
			// create and define the collision.
			collisions = new SphereCollision( player, 15, new Vector3D( 0, 15, 0 ) );
			
			// test the collisions with entire level.
			collisions.addCollisionWith( level );
			
			// update the scene.
			scene.addEventListener( Scene3D.UPDATE_EVENT, updateEvent );
		}
		
		private function updateEvent(e:Event):void 
		{
			// rotate and translate the player.
			if ( Input3D.keyDown( Input3D.RIGHT ) ) { player.rotateY( 5 ); player.frameSpeed = 1; }
			if ( Input3D.keyDown( Input3D.LEFT ) ) { player.rotateY( -5 ); player.frameSpeed = 1; }
			if ( Input3D.keyDown( Input3D.UP ) ) { player.translateZ( 4 ); player.frameSpeed = 1; }
			if ( Input3D.keyDown( Input3D.DOWN ) ) { player.translateZ( -4 ); player.frameSpeed = -1; }
			
			// if some key is pressed, play the animation.
			if ( Input3D.keyDown( Input3D.UP ) || 
				 Input3D.keyDown( Input3D.DOWN ) || 
				 Input3D.keyDown( Input3D.LEFT ) || 
				 Input3D.keyDown( Input3D.RIGHT ) ) 
				player.play();
			else
				player.stop();				
			
			// like gravity.
			player.y -= 3
			
			// once we moved the player, we test for collisions 
			collisions.slider();
			
			/**** simple camera managment ****/
			
			// set the camera position relative to the player.
			Pivot3DUtils.setPositionWithReference( scene.camera, 0, 600, -600, player, 0.1 );
			
			// orientate the camera to player position.
			Pivot3DUtils.lookAtWithReference( scene.camera, 0, 0, 0, player );
		}
	}
}